﻿package com.cilico.single.view;

import java.util.Vector;

import android.view.View;

import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.R;
import com.cilico.single.components.Alert;
import com.cilico.single.components.Component;
import com.cilico.single.components.DatePicker;
import com.cilico.single.components.Label;
import com.cilico.single.components.POI;
import com.cilico.single.components.Radio;
import com.cilico.single.components.Select;
import com.cilico.single.components.TimePicker;
import com.cilico.single.components.WaitDialog;
import com.cilico.single.components.cCheckBox;
import com.cilico.single.components.mButton;
import com.cilico.single.components.mTextField;
import com.cilico.single.shopcart.ShopCartList;
import com.cilico.single.utils.ConstantRepository;
import com.cilico.single.utils.PackageManagerAndroid;
import com.cilico.single.utils.Utils;

/**
 * 表单提交
 * @author lv.xiangan
 *
 */
public class FormAction {
	Mid mid_;
	BaseView bv_;
	public String name_;
	public String action_;
	public String hidden_;
	public Vector<Component> itemV_; // 当前Form中的component
	public boolean isHidden_;

	/** Creates a new instance of FormAction */
	public FormAction(Mid mid, BaseView bv) {
		mid_ = mid;
		bv_ = bv;
	}

	public void addItem(Component c) {
		if (itemV_ == null)
			itemV_ = new Vector<Component>();
		itemV_.addElement(c);
	}

	// 向界面中层框架中填充控件
	// BaseView：界面元素
	// View：需要填充的控件
	// void addView(BaseView bv, View view) {
	// bv_ = bv;
	// bv_.appendAtFixP(view);
	// }

	boolean isInFormAction(View c) {
		if (itemV_ != null) {
			for (int i = 0; i < itemV_.size(); i++) {
				View temp = (View) itemV_.elementAt(i);
				if (c == temp)
					return true;
			}
		}
		return false;
	}

	private void initHiddenValue(View c) {
		if (!(c instanceof Label) || itemV_ == null) {
			return;
		}
		Label label = (Label) c;
		if (!label.isValueLabel_) {
			return;
		}
		for (int i = 0; i < itemV_.size(); i++) {
			Component temp = (Component) itemV_.elementAt(i);
			if (temp instanceof mTextField) {
				mTextField comp = (mTextField) temp;
				if (comp.attrName_ == null || !comp.attrName_.equals(label.attrName_)) {
					continue;
				}
				String value = comp.getContentText().trim();
				if (value.equals(bv_.getString(R.string.touchinput)))
					value = "";
				label.setText(value);
				label.attrValue_ = value;
			} else if (temp instanceof cCheckBox) {
				cCheckBox comp = (cCheckBox) temp;
				if (comp.attrName_ == null || !comp.attrName_.equals(label.attrName_)) {
					continue;
				}
				if (!comp.isChecked()) {
					continue;
				}
				label.setText(temp.getContentText());
				label.attrValue_ = comp.attrValue_;
			} else if (temp instanceof Radio) {
				Radio comp = (Radio) temp;
				if (comp.attrName_ == null || !comp.attrName_.equals(label.attrName_)) {
					continue;
				}
				if (!comp.isChecked()) {
					continue;
				}
				label.setText(temp.getContentText());
				label.attrValue_ = comp.attrValue_;
			} else if (temp instanceof Select) {
				Select comp = (Select) temp;
				if (comp.attrName_ == null || !comp.attrName_.equals(label.attrName_)) {
					continue;
				}
				Select.Option o = (Select.Option) comp.dropdownMenuText_.elementAt(((Select) temp).currentMenu_);
				label.setText(o.label_);
				label.attrValue_ = o.value_;
			}
			break;
		}
	}

	void PostForm(mButton btn, BaseView bv) {
		bv_ = bv;
		try {
			if (btn.buttonType_ == null)
				return;
			if (bv_ instanceof DetailView) {
				postDetailViewForm(btn);
			} else if (bv_ instanceof LoginView) {
				postLoginViewForm(btn);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
	}

	/**
	 * @param btn
	 */
	private void postDetailViewForm(mButton btn) throws Exception {
		DetailView detailView_ = (DetailView) bv_;
		if (btn.buttonType_.equals("reset")) {
			detailView_.populate(detailView_.currentDisplayPoi_);
			Utils.addManagerAndSetTop(detailView_);
		} else if (btn.buttonType_.equals("cancel")) {
			mid_.poiRepo_.removeAllActionPoi();// clear stack.
			DisplayPoi dp = mid_.getCurrentPoiSelection(false, bv_).getCurrentPOI();
			POI poi = null;
			if (dp != null && dp.poi_ != null)
				poi = dp.poi_;
			else
				poi = detailView_.currentDisplayPoi_;
			detailView_.populate(poi);
			detailView_.llScreen_.postInvalidate();
			Utils.addManagerAndSetTop(detailView_);
		} else if (name_ != null && !isHidden_) {
			FormAction faction = detailView_.getHiddenFormByName(name_);
			if (faction != null && faction.itemV_ != null) {
				detailView_.tabBar_.removeAllContentChild();
				for (int i = 0; i < faction.itemV_.size(); i++) {
					View tem = (View) faction.itemV_.elementAt(i);
					initHiddenValue(tem);
					detailView_.appendAtFixP(tem);
				}
			} else if (action_ != null) {
				String info = isInputCorrect(btn);
				if (info != null) {
					mid_.alert(detailView_, info, false);
				} else {
					sendForm(btn, bv_);
				}
			}
		} else if (btn.attrName_ != null && btn.attrName_.equals("ewp_relogin")) {
			BaseView.mid_.waitDialog_.setText("登录中..");
			BaseView.mid_.waitDialog_.addFgTask(bv_, new WaitDialog.Task(0) {

				public void run(WaitDialog dlg) throws Exception {
					BaseView.mid_.waitDialog_.setText("登录中..");
					// 该处重新显示登录界面，应该将以前存储的poi全部清空，再重新执行起登录界面步骤，将该界面关闭。
					mid_.gotoRelogin(bv_);
				}
			}, false);
			return;
		} else if (action_ != null) {
			String info = isInputCorrect(btn);
			if (info != null) {
				mid_.alert(bv_, info, false);
			} else {
				sendForm(btn, bv_);
			}
		}
	}

	/**
	 * @param btn
	 */
	private void postLoginViewForm(mButton btn) throws Exception {
		LoginView loginView_ = (LoginView) bv_;
		if (btn.attrName_ != null && btn.attrName_.equals("ewp_relogin")) {
			BaseView.mid_.waitDialog_.setText("登录中..");
			BaseView.mid_.waitDialog_.addFgTask(bv_, new WaitDialog.Task(0) {

				public void run(WaitDialog dlg) throws Exception {
					BaseView.mid_.waitDialog_.setText("登录中..");
					// 该处重新显示登录界面，应该将以前存储的poi全部清空，再重新执行起登录界面步骤，将该界面关闭。
					mid_.gotoRelogin(bv_);
				}

			}, false);
			return;
		}
		if (btn.buttonType_.equals("reset")) {
			loginView_.populate(loginView_.currentDisplayPoi_);
		} else if (btn.buttonType_.equals("cancel")) {
			mid_.poiRepo_.removeAllActionPoi();// clear stack.
			DisplayPoi dp = mid_.getCurrentPoiSelection(false, bv_).getCurrentPOI();
			POI poi = null;
			if (dp != null && dp.poi_ != null)
				poi = dp.poi_;
			else
				poi = loginView_.currentDisplayPoi_;
			loginView_.populate(poi);
		} else if (name_ != null && !isHidden_) {
			FormAction faction = loginView_.getHiddenFormByName(name_);
			if (faction != null && faction.itemV_ != null) {
				loginView_.tabBar_.removeAllContentChild();
				for (int i = 0; i < faction.itemV_.size(); i++) {
					View tem = (View) faction.itemV_.elementAt(i);
					initHiddenValue(tem);
					loginView_.appendAtFixP(tem);
				}
			} else if (action_ != null) {
				String info = isInputCorrect(btn);
				if (info != null) {
					mid_.alert(bv_, info, false);

				} else {
					sendFormInLogingView(btn, bv_);
				}
			}
		} else if (action_ != null) {
			String info = isInputCorrect(btn);
			if (info != null) {
				Alert.ISEXIT = false;
				mid_.alert(bv_, info, false);
			} else {
				sendFormInLogingView(btn, bv_);
			}
		}
	}

	private void sendFormInLogingView(final mButton btn, final BaseView bv) {
		BaseView.mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {

			@Override
			public void run(WaitDialog dlg) throws Exception {
				// TODO Auto-generated method stub
				sendLoginMessage(bv, btn, this);
			}

			public void onSuccess(WaitDialog dlg) {
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.handleLoginFailure(bv, getErrMsg());
				super.onFailure(dlg);
			}
		}, false);
	}

	private void sendForm(final mButton btn, final BaseView bv) {
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				sendDetailView(bv, btn, this);
			}

			public void onSuccess(WaitDialog dlg) {
				// 如果是刷新按钮，则压入pop，等数据回来时做弹栈的条件
				if ("刷新".equals(btn.attrValue_)) {
					mid_.poiRepo_.pushActionPoi("pop");
				}
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				// mid_.alert(bv, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false, btn.isNoCancel_);

		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}


	private void sendLoginMessage(BaseView bv, mButton btn, WaitDialog.Task task) throws Exception {
		StringBuffer buf = new StringBuffer();
		int sz = itemV_.size();
		for (int i = 0; i < sz; i++) {
			View attItem = (View) itemV_.elementAt(i);
			if (attItem == btn)
				break;
			if (!attItem.isShown())
				continue;
			if (attItem instanceof mTextField) {
				mTextField ltf = (mTextField) attItem;
				buf.append(ltf.attrName_);
				buf.append("=");
				String value ;
				if ((ltf.mask_) && (ltf.attrTrueValue_ != null)) {
					value = ltf.attrTrueValue_;
				} else {
					value = ltf.getContentText().trim();
				}
				if (null != btn.attrName_ && btn.attrName_.equals("ewp_login_app") && null != ltf.attrName_ && ltf.attrName_.equals("mobileNo")){
					BaseView.phonenum_ = value;
				}
				if (value.equals(bv_.getString(R.string.touchinput)))
					value = "";
				buf.append(Utils.escapeURIComponent(value));
				buf.append("&");
			} else if ((attItem instanceof cCheckBox && ((cCheckBox) attItem).isChecked())) {
				cCheckBox chebx = (cCheckBox) attItem;
				buf.append(chebx.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent((chebx.attrValue_)));
				buf.append("&");
			} else if ((attItem instanceof Radio && ((Radio) attItem).isChecked())) {

				Radio radio = (Radio) attItem;
				if (radio.attrSave_ && radio.isChecked()) {
					// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象

					if (null != Mid.saveProperty_ && null != name_ && null != action_
							&& null != radio.attrName_) {
						Mid.saveProperty_.put(name_.concat(action_).concat(radio.attrName_),
								radio.isChecked());
					}
				}
				buf.append(radio.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(radio.attrValue_));
				buf.append("&");
				buf.append("&");
			} else if (attItem instanceof SegmentLinearLayout) {
				SegmentLinearLayout sll = (SegmentLinearLayout) attItem;
				final int sizeSll = sll.getChildCount();
				View view;
				for (int j = 0; j < sizeSll; j++) {
					view = sll.getChildAt(j);
					Radio radio = (Radio) view;
					if (radio.isChecked()) {
						if (radio.attrSave_) {
							// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象

							if (null != Mid.saveProperty_ && null != name_ && null != action_
									&& null != radio.attrName_) {
								Mid.saveProperty_.put(name_.concat(action_).concat(radio.attrName_),
										radio.isChecked());
							}
						}
						buf.append(radio.attrName_);
						buf.append("=");
						buf.append(Utils.escapeURIComponent(radio.attrValue_));
						buf.append("&");
					}
				}
			} else if (attItem instanceof Select) {
				Select select = (Select) attItem;
				buf.append(select.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(((Select.Option) select.dropdownMenuText_.elementAt(select.currentMenu_)).value_));
				buf.append("&");
			} else if (attItem instanceof Label && ((Label) attItem).isValueLabel_) {
				Label label = (Label) attItem;
				buf.append(label.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(label.attrValue_));
				buf.append("&");
			}
		}
//		Utils.saveProperties(bv, itemV_);
//		Utils.saveProperties(bv, str);
		// summit the button name and value.
		if (btn.attrName_ != null) {
			buf.append(btn.attrName_);
			buf.append("=");
			buf.append(Utils.escapeURIComponent(btn.attrValue_));
			buf.append("&");
			// 解决注册成功之后点击立即登录返回到登录页面依然显示tabBar的问题
			if (btn.attrName_.equals("notopbar")) {
				while (BaseView.mid_.poiRepo_.actionV_.size() > 0) {
					BaseView.mid_.poiRepo_.popActionPoi();
				}
			}
		}
		
		
		// add hidden.
		if (hidden_ != null){
			buf.append(hidden_);	
		}
		// delete the last '&'.
		if (buf.length() > 0 && buf.charAt(buf.length() - 1) == '&') {
			buf.deleteCharAt(buf.length() - 1);
		}
		String body = buf.toString();
		Utils.printOutToConsole("body ====LLL " + body);
		buf.delete(0, buf.length());
		if (action_.startsWith(ConfigManager.SERVER_URI + "atompub/form")
				||action_.startsWith(ConfigManager.SERVER_URI.substring(0, ConfigManager.SERVER_URI.indexOf(':')) + "atompub/form")) {
			buf.append(action_);
		} else if (action_.startsWith("channel:")) {
			if (action_.indexOf('?') == -1)
				action_ += "?";
			// switch channel.
			String shortCut = getShortCut(action_);
			String url = "http" + action_.substring(7);
			// add _s for the controllers.
			// channel 跳转时改成全部加密。
			String temphost = url;
			int indexC = url.indexOf("/channel/");
			int indexA = url.indexOf("/atompub/");
			if (indexC != -1) {
				temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
			} else if (indexA != -1) {
				temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
			}
			url = temphost;
			mid_.channelEntity_.switchChannel(bv, shortCut, true, url, body, btn.isNoCancel_);
			return;
		} else if (action_.indexOf("/runc") != -1) {
			if (!action_.startsWith("http://")) {
				buf.append(ConfigManager.SERVER_URI);
			}
			buf.append(action_);
		} else if (action_.contains("getui") || action_.contains("getuc")) {
			// 如果地址里面含以上条件参数则不需替换。
			buf.append(action_);
		} else if (action_.endsWith("/question")) {
			buf.append(action_);
		} else if (btn.attrName_ != null && btn.attrName_.length() > 0 && btn.attrName_.endsWith("ewp_login_app")) {
			// 登录。
			if(ConfigManager.DEVICETOKEN != null && ConfigManager.DEVICETOKEN.length() > 0){
				body += "&devicetoken=" + ConfigManager.DEVICETOKEN;
			}
			// 品牌
			body += "&devicebrand=" + android.os.Build.BRAND;
			// 型号
			body += "&devicemodel=" + android.os.Build.MODEL;
			// 系统版本
			body += "&devicesystemversion=" + android.os.Build.VERSION.RELEASE;
			// 操作系统
			body += "&devicesystemname=android";
			body = body.replace(' ', '-');
			buf.append(action_);
			// return;
		} else if (action_.startsWith(ConfigManager.SERVER_URI)
				||action_.startsWith(ConfigManager.SERVER_URI.substring(0, ConfigManager.SERVER_URI.indexOf(':')))) {
			buf.append(action_);
		} else {
			buf.append(ConfigManager.SERVER_URI);
			buf.append("atompub/form?c=");
			if (null != mid_.poiRepo_.channel_)
				buf.append(mid_.poiRepo_.channel_.id());
			buf.append("&n=");
			buf.append(Utils.escapeURIComponent(action_));
		}
		Channel ch = mid_.topChannelRepo_.getCurrentChannel();
		String host = buf.toString();
		// add _s for the controllers.
		if (null != ch || host.indexOf("/atompub/") != -1 || host.indexOf("/gdb/") != -1) {
			// if (ch.isSecure_) {
			String temphost = host;
			int indexC = host.indexOf("/channel/");
			int indexA = host.indexOf("/atompub/");
			int indexG = host.indexOf("/gdb/");
			if (indexC != -1) {
				temphost = host.substring(0, indexC) + "/channel_s/" + host.substring(indexC + "/channel/".length());
			} else if (indexA != -1) {
				temphost = host.substring(0, indexA) + "/atompub_s/" + host.substring(indexA + "/atompub/".length());
			} else if (indexG != -1){
				temphost = host.substring(0, indexG) + "/gdb_s/" + host.substring(indexG + "/gdb/".length());
			}
			host = temphost;
		}
		boolean isSignIn = false;
		if (btn.attrName_ != null && btn.attrName_.length() > 0 && btn.attrName_.endsWith("ewp_login_app")) {
			isSignIn = true;
			mid_.updateMode_ = false;
		} else if (btn.attrValue_.equalsIgnoreCase("下次更新")) {
			// 用户点击下次更新按钮
			// 解决点击下次更新回到登录页面时显示tabBar问题。
			BaseView.mid_.poiRepo_.popActionPoi();
		} else if (btn.attrValue_.indexOf(bv.getString(R.string.enter)) != -1) {
			isSignIn = true;
		} else if (btn.attrValue_.indexOf(bv.getString(R.string.menuRegister)) != -1) {
			isSignIn = true;
		}
		mid_.processLogin(host, body, isSignIn, bv,itemV_);
	}

	/**
	 * 这个方法在用户注册时查看客户须知的时候调用，保存用户输入的注册数据
	 * */
	void saveRegistDataToPropertyTemp(BaseView bv) {
		int sz = itemV_.size();
		for (int i = 0; i < sz; i++) {
			View attItem = (View) itemV_.elementAt(i);
			if (attItem instanceof mTextField) {
				mTextField ltf = (mTextField) attItem;
				String value = ltf.getContentText().trim();

				if (ltf.attrSave_) {
					// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象
					if (null != Mid.savePropertyTemp_ && null != name_ && null != action_ && null != ltf.attrName_) {
						Mid.savePropertyTemp_.put(name_.concat(action_).concat(ltf.attrName_), value);
					}
				}

			}
		}
	}

	private void sendDetailView(BaseView bv, mButton btn, WaitDialog.Task task) throws Exception {
		StringBuffer buf = new StringBuffer();
		int sz = itemV_.size();
		for (int i = 0; i < sz; i++) {
			View attItem = (View) itemV_.elementAt(i);
			if (attItem == btn)
				break;
			if (!attItem.isShown() && !(attItem instanceof Radio) && !(attItem instanceof cCheckBox)) {
				continue;
			}
			if (attItem instanceof mTextField) {
				mTextField ltf = (mTextField) attItem;
				String value;
				buf.append(ltf.attrName_);
				buf.append("=");
				if (ltf.mask_ && ltf.attrTrueValue_ != null) {
					value = ltf.attrTrueValue_;
				} else {
					value = ltf.getContentText().trim();
				}
				if (value.equals(bv_.getString(R.string.touchinput)))
					value = "";
				if((ltf.getMyInputType() == ConfigManager.InputType_DECIMAL ) && value.contains(".")) {
					String subStr = value.substring(value.indexOf('.') + 1);
					if (subStr != null && subStr.length() <= 1){
	                    if (subStr.length() == 0){
	                    	subStr = subStr + "00";
	                    } else if (subStr.length() == 1){
	                    	subStr = subStr + "0";
	                    }
	                    value = value.substring(0,value.indexOf('.') + 1).concat(subStr);
					}
				}
				buf.append(Utils.escapeURIComponent(value));
				buf.append("&");
				Mid.savePropertyTemp_.put(ltf.attrName_, value.trim());
			} else if ((attItem instanceof cCheckBox && ((cCheckBox) attItem).isChecked())) {
				cCheckBox chebx = (cCheckBox) attItem;
				buf.append(chebx.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(chebx.attrValue_));
				buf.append("&");
			} else if ((attItem instanceof Radio && ((Radio) attItem).isChecked())) {
				Radio radio = (Radio) attItem;
				if (radio.attrSave_ && radio.isChecked()) {
					// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象
					if (null != Mid.savePropertyTemp_ && null != name_ && null != action_
							&& null != radio.attrName_) {
						Mid.savePropertyTemp_.put(name_.concat(action_).concat(radio.attrName_),
								radio.isChecked()); 
					}
				}
				buf.append(radio.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(radio.attrValue_));
				buf.append("&");
				buf.append("&");
			} else if (attItem instanceof SegmentLinearLayout) {
				SegmentLinearLayout sll = (SegmentLinearLayout) attItem;
				final int sizeSll = sll.getChildCount();
				View view;
				for (int j = 0; j < sizeSll; j++) {
					view = sll.getChildAt(j);
					Radio rdio = (Radio) view;
					if (rdio.isChecked()) {
						if (rdio.attrSave_) {
							// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象
							if (null != Mid.savePropertyTemp_ && null != name_ && null != action_
									&& null != rdio.attrName_) {
								Mid.savePropertyTemp_.put(name_.concat(action_).concat(rdio.attrName_),
										rdio.isChecked());
							}
						}
						buf.append(rdio.attrName_);
						buf.append("=");
						buf.append(Utils.escapeURIComponent(rdio.attrValue_));
						buf.append("&");
					}
				}
			} else if (attItem instanceof Select) {
				Select selet = (Select) attItem;
				buf.append(selet.attrName_);
				buf.append("=");
				if (!selet.dropdownMenuText_.isEmpty()) {
					buf.append(Utils.escapeURIComponent(((Select.Option) selet.dropdownMenuText_.elementAt(selet.currentMenu_)).value_));
				}
				buf.append("&");
				if (selet.attrSave_||selet.attrTrueSave_) {
					// 如果xml报文显示save为yes，则将该页面的form名称和url以及下拉框控件名称组成一个键名。键值用选中的option对象
					if (null != Mid.savePropertyTemp_ && null != this.action_&& null != selet.attrName_) {	
						if (selet.attrTrueSave_ && null != selet.tableName_){
							Mid.savePropertyTemp_.put(action_.concat(selet.tableName_).concat(selet.attrName_),
									((Select.Option) selet.dropdownMenuText_.elementAt(selet.currentMenu_)).label_);
						} else{
							Mid.savePropertyTemp_.put(action_.concat(selet.attrName_), ((Select.Option) selet.dropdownMenuText_.elementAt(selet.currentMenu_)).label_);
						}
					}
				}
			} else if (attItem instanceof Label && ((Label) attItem).isValueLabel_) {
				Label label = (Label) attItem;
				buf.append(label.attrName_);
				buf.append("=");
				buf.append(Utils.escapeURIComponent(label.attrValue_));
				buf.append("&");
			} else if (attItem instanceof DatePicker) {
				DatePicker temp = (DatePicker) attItem;
				buf.append(temp.attrName_);
				buf.append("=");
				buf.append(temp.attrValue_);
				buf.append("&");
			}else if (attItem instanceof TimePicker) {
				TimePicker temp = (TimePicker) attItem;
				buf.append(temp.attrName_);
				buf.append("=");
				buf.append(temp.attrValue_);
				buf.append("&");
			}else if (attItem instanceof ShopCartList) {
				ShopCartList temp = (ShopCartList) attItem;
				buf.append(temp.attrName_);
				buf.append("=");
//				buf.append(temp.attrValue_);
				buf.append(Utils.escapeURIComponent(temp.postData_));
				buf.append("&");
			}
		}
		// 存储xml相关属性
		Utils.saveProperties(bv, itemV_);
		// 检查
		// summit the button name and value.
		if (btn.attrName_ != null) {
			buf.append(btn.attrName_);
			buf.append("=");
			buf.append(Utils.escapeURIComponent(btn.attrValue_));
			buf.append("&");
			if (btn.attrName_.equals("preferential_1") || btn.attrName_.equals("preferential_2")
					||btn.attrName_.equals("preferential_3")) {
				//添加优惠份数
				for (int i = 0; i < bv_.vWidgetArray_.size(); i++) {
					Object object = bv_.vWidgetArray_.get(i);
					if (object instanceof mTextField) {
						mTextField textField = (mTextField) object;
						if (textField.attrName_!= null && 
								textField.attrName_.equals("copies")) {
							buf.append("copies");
							buf.append("=");
							buf.append(Utils.escapeURIComponent(textField.getText().toString()));
							buf.append("&");
							break;
						}
					}
				}
			}
		}
		// add hidden.
		if (hidden_ != null) {
			buf.append(hidden_);
			buf.append("&");
		}

		//拼接点餐json
		if (btn.getJson_ != null && !btn.getJson_.equals("")) {
			buf.append("json");
			buf.append("=");
			buf.append(BaseView.mid_.pm_.SAVEPROPERTYDB_.
					get(PackageManagerAndroid.SHOPCART_REAL_DB));
			buf.append("&");
			Utils.printOutToConsole("提交菜品json---->>>>"+BaseView.mid_.pm_.SAVEPROPERTYDB_.
					get(PackageManagerAndroid.SHOPCART_REAL_DB));
		}
		// delete the last '&'.
		if (buf.length() > 0 && buf.charAt(buf.length() - 1) == '&') {
			buf.deleteCharAt(buf.length() - 1);
		}
		
		String body = buf.toString();
		buf.delete(0, buf.length());
		
		// 读取本地页面
		if (action_.startsWith("local://")) {
			mid_.channelEntity_.sendForm(action_, body, btn.isNoCancel_, bv, false);
			return;
		}
		
		if (action_.startsWith(ConfigManager.SERVER_URI + "atompub/form") ||action_.startsWith(ConfigManager.SERVER_URI.substring(0, ConfigManager.SERVER_URI.indexOf(':')) + "atompub/form")) {
			buf.append(action_);
		} else if (action_.startsWith("channel:")) {
			if (action_.indexOf('?') == -1)
				action_ += "?";
			// switch channel.
			String shortCut = getShortCut(action_);
			String url = "http" + action_.substring(7);
			String temphost = url;
			int indexC = url.indexOf("/channel/");
			int indexA = url.indexOf("/atompub/");
			if (indexC != -1) {
				temphost = url.substring(0, indexC) + "/channel_s/" + url.substring(indexC + "/channel/".length());
			} else if (indexA != -1) {
				temphost = url.substring(0, indexA) + "/atompub_s/" + url.substring(indexA + "/atompub/".length());
			}
			url = temphost;
			mid_.channelEntity_.switchChannel(bv, shortCut, true, url, body, btn.isNoCancel_);
			return;
		} else if (action_.indexOf("/runc") != -1) {
			if (!action_.startsWith("http://")) {
				buf.append(ConfigManager.SERVER_URI);
			}
			buf.append(action_);
		} else if (action_.startsWith(ConfigManager.SERVER_URI) ||action_.startsWith(ConfigManager.SERVER_URI.substring(0, ConfigManager.SERVER_URI.indexOf(':')))) {
			buf.append(action_);
		} else if (action_.equalsIgnoreCase("define")) {//处理点餐的本地页面
			//特殊处理餐厅点餐，提交数据,下一步按钮
			buf.append(BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.LOGIN_URL));
			if (!buf.toString().endsWith("?")) {
				buf.append("?");
			}
			buf.append("loginType");
			buf.append("=");
			buf.append(btn.loginType_);
			buf.append("&");
			buf.append("restaurantId");
			buf.append("=");
			buf.append(BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.RESTAURANT_USER_ID));
			buf.append("&");
		}else {
			buf.append(ConfigManager.SERVER_URI);
			buf.append("atompub/form?user=");
			if (null != mid_.poiRepo_.channel_)
				buf.append(mid_.poiRepo_.channel_.id());
			buf.append("&n=");
			buf.append(Utils.escapeURIComponent(action_));
			//----Original------/
//			buf.append(ConfigManager.SERVER_URI);
//			buf.append("atompub/form?c=");
//			if (null != mid_.poiRepo_.channel_)
//				buf.append(mid_.poiRepo_.channel_.id());
//			buf.append("&n=");
//			buf.append(Utils.escapeURIComponent(action_));
		}
		
		String host = buf.toString();
		String temphost = host;
		int indexC = host.indexOf("/channel/");
		int indexA = host.indexOf("/atompub/");
		if (indexC != -1) {
			temphost = host.substring(0, indexC) + "/channel_s/" + host.substring(indexC + "/channel/".length());
		} else if (indexA != -1) {
			temphost = host.substring(0, indexA) + "/atompub_s/" + host.substring(indexA + "/atompub/".length());
		}
		host = temphost;
		if (host.indexOf("/gdb_s/getui") != -1) {
			BaseView.mid_.um_.switchUIVIew(bv, host, body);
		} else {
			mid_.channelEntity_.sendForm(host, body, btn.isNoCancel_, bv, false);
		}
	}


	private String getShortCut(String url) {
		// URL syntax: channel://host/atompub/chform/channel_shortcut? or URL
		// syntax: channel://host/atompub/chform/channel_shortcut/...?
		final String chform = "chform/";
		int id1 = url.indexOf(chform);
		int id2 = -1;
		int tmp = url.indexOf('/', id1 + chform.length());
		int tmp1 = url.indexOf('/', tmp);
		if (id1 != -1 && tmp == -1) {
			id2 = url.indexOf("?", id1 + chform.length()) == -1 ? url.length() : url
					.indexOf("?", id1 + chform.length());
		} else {
			id2 = tmp1;
		}
		String ch_shortCut = null;
		if (id1 != -1 && id2 > id1)
			ch_shortCut = url.substring(id1 + chform.length(), id2);
		return ch_shortCut;
	}

	// stop when reach the component btn.
	private String isInputCorrect(View btn) {
		String info = null;
		int len = 0;
		int constraint = 0;
		int error = 0;
		int sz = itemV_.size();
		for (int i = 0; i < sz; i++) {
			View attItem = (View) itemV_.elementAt(i);
			if (attItem == btn)
				break;
			if (!attItem.isShown())
				continue;
			if (attItem instanceof mTextField) {
				mTextField tf = (mTextField) attItem;
				if (tf.required_) {
					constraint = tf.getMyInputType();
					String value = tf.getContentText().trim();
					if (constraint == ConfigManager.InputType_PHONE) {
						// the phone number length should be 11.
                        if(value == null || value.equals("")){
							info = "手机号为空，请重新输入";
							error = 3;		
						} else if (value.length() != 11) {
							info = "手机号码输入有误，请重新输入";
							error = 3;
						} else if (value.length() == 11){
							for (int l = value.length() - 1; l >= 0; l--) {
								if (!(value.charAt(l) >= '0' && value.charAt(l) <= '9')) {// 不能包含非数字字符
									info = "手机号中含非数字字符，请重新输入";
									error = 3;
								}
							}
						}
					} else if (value == null || value.length() == 0 || value.equals(bv_.getString(R.string.touchinput))) {
						error = 1;
						View item = (View) itemV_.elementAt(i - 1);
						if (item instanceof Label) {
							Label label = (Label) item;
							info = label.getContentText();
						} else if(item instanceof Select) {
							Select slect = (Select)item;
							if(null != slect.attrAccessory_ && slect.attrAccessory_.startsWith("cusv_select://")) {
								View item2 = (View) itemV_.elementAt(i - 2);
								if (item2 instanceof Label) {
									Label label = (Label) item2;
									info = label.getContentText();
									label = null;
								}
								item2 = null;
							}
							slect = null;
						}
					} else {
						if (value.length() < tf.minSize_) {
							error = 2;
							len = tf.minSize_;
							View tempLabel = (View) itemV_.elementAt(i - 1);
							if (tempLabel instanceof Label) {
								Label lbel = (Label) tempLabel;
								info = lbel.getContentText();
							} else if(tempLabel instanceof Select) {
								Select selet = (Select)tempLabel;
								if(null != selet.attrAccessory_ && selet.attrAccessory_.startsWith("cusv_select://")) {
									View item2 = (View) itemV_.elementAt(i - 2);
									if (item2 instanceof Label) {
										Label label = (Label) item2;
										info = label.getContentText();
										label = null;
									}
									item2 = null;
								}
								selet = null;
							}
						} else if (tf.textFieldType_ != null && tf.textFieldType_.equals("password")) {
							for (int l = value.length() - 1; l >= 0; l--) {
								if (!((value.charAt(l) >= '0' && value.charAt(l) <= '9')
										|| (value.charAt(l) >= 'a' && value.charAt(l) <= 'z') || (value.charAt(l) >= 'A' && value
										.charAt(l) <= 'Z'))) {// 不能包含特殊字符
									error = 5;
								}
							}
						} else if (constraint == ConfigManager.InputType_NUMBER){
							if (tf.mask_){
								value = tf.attrTrueValue_;
							}
							for (int l = value.length() - 1; l >= 0; l--) {
								if (!(value.charAt(l) >= '0' && value.charAt(l) <= '9')) {// 不能包含非数字字符
									View tempLabel = (View) itemV_.elementAt(i - 1);
									if (tempLabel instanceof Label) {
										Label label = (Label) tempLabel;
										info = label.getContentText();
										error = 8;
									}
									
								}
							}	
						}
					}
				}
			}
			
			if (error > 0) {
				if (info == null && i > 0) {
					View item = (View) itemV_.elementAt(i - 1);
					if (item instanceof Label) {
						Label label = (Label) item;
						info = label.getContentText();
					}
				}
				if (info == null || info.trim().length() == 0) {
					if (error == 1)
						info = "您的输入不完整，请重新输入！";
					else
						info = "您的输入不正确，请重新输入！";
				} else if (error != 3) {
					info = info.trim();
					int n = info.length();
					char c = info.charAt(n - 1);
					if (c == ':' || c == '：') // remove ':' or '：'.
						info = info.substring(0, n - 1);
					if (error == 1) {
						info += "不能为空";
					} else if (error == 2) {
						switch (constraint) {
						case ConfigManager.InputType_NUMBER:
						case ConfigManager.InputType_DECIMAL:
						case ConfigManager.InputType_VARIATION_VISIBLE_PASSWORD:
						case ConfigManager.InputType_VARIATION_VISIBLE_PASSWORD | ConfigManager.InputType_NUMBER:
							info += "输入的数字长度不能小于".concat(String.valueOf(len)).concat("位");
							break;
						default:
							info += "输入的字符个数不能小于".concat(String.valueOf(len)).concat("个");
							break;
						}
					} else if (error == 4){
						info = info + "的输入长度不能小于".concat(String.valueOf(len)).concat("位");
					} else if (error == 5) {
						info =  info + "不能包含除数字和字母以外的字符，请重新输入！";
					} else if (error == 6) {
						info = "预约码的输入长度不能小于".concat(String.valueOf(len)).concat("位");
					} else if (error == 7) {
						info = "输入有误，最少输入.".concat(String.valueOf(len)).concat("位");
					} else if (error == 8) {
						info = info + "中含有非数字字符，请重新输入！";
					}
				}
				// bv_.setCurrentItem(attItem); // Set it as the focus item.
				attItem.requestFocus();
				return info;
			}
		}
		return null;
	}




}
